package com.vanrui.pcp.autocode.jdbc;

import java.sql.Connection;
import java.sql.DriverManager;

import org.apache.log4j.Logger;

import com.vanrui.pcp.autocode.model.entry.JdbcConfig;


public class JDBCUtil {
	
	private final static Logger logger = Logger.getLogger(JDBCUtil.class);
	
	private static JDBCUtil jdbcUtil = null;
	private Connection conn = null;
	private JdbcConfig jdbcConfig;
	private Object connectLock = new Object();
	private static Object instanceLock = new Object();
	
	
	private JDBCUtil() throws Exception{
		if(jdbcUtil != null){
			throw new Exception("实例已存在");
		}
	}
	
	
	private JDBCUtil(JdbcConfig jdbcConfig) throws Exception {
		if(jdbcUtil != null){
			throw new Exception("实例已存在");
		}
		this.jdbcConfig = jdbcConfig;
	}


	public Connection getConn() throws Exception {
		if(conn == null){
			synchronized (connectLock) {
				if(conn == null){
					try {
						Class.forName(jdbcConfig.getDriver());
						conn = DriverManager.getConnection(jdbcConfig.getUrl(), jdbcConfig.getUser(), jdbcConfig.getPassword());
					} catch (Exception e) {
						 logger.info("创建数据库连接失败！");
						 throw new Exception(e);
					}
				}
			}
		}
		return conn;
	}
	
	public static JDBCUtil getInstance(JdbcConfig jdbcConfig) throws Exception{
		if(jdbcUtil == null){
			synchronized(instanceLock){
				if(jdbcUtil == null){
					jdbcUtil = new JDBCUtil(jdbcConfig);
				}
			}
		}
		return jdbcUtil;
	}

}
